import 'package:easy_chat_app/commons/GlobalStatus.dart';
import 'package:easy_chat_app/commons/db/repository/LocalConversationRepository.dart';
import 'package:easy_chat_app/commons/db/service/LocalConversationService.dart';
import 'package:easy_chat_app/commons/model/AppUserDetail.dart';
import 'package:easy_chat_app/commons/model/Conversation.dart';
import 'package:easy_chat_app/commons/model/GetContactsListItem.dart';
import 'package:easy_chat_app/commons/utils/HttpUtils.dart';
import 'package:easy_chat_app/commons/utils/ListUtils.dart';
import 'package:easy_chat_app/commons/utils/RouteUtils.dart';
import 'package:easy_chat_app/commons/utils/StringUtils.dart';
import 'package:easy_chat_app/commons/widget/UserHeadPortrait.dart';
import 'package:easy_chat_app/mobile/constants/MobileAppGlobalConstants.dart';
import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'package:provider/provider.dart';

class MobileCreateChatGroupPageParams {}

class MobileCreateChatGroupPageData {}

class ContactsView {
  // 0 拼音 1 联系人 2 系统内置选项
  int? type;
  int? contactId;
  String? contactCode;
  String? typeCode;
  String? typeName;
  String? assetImg;
  String? py;
  String? nickname;
  String? headPortrait;
  String? headPortraitStoreType;
  bool showBorder = true;

  @override
  String toString() {
    return 'ContactsView{type: $type, contactId: $contactId, contactCode: $contactCode, typeCode: $typeCode, typeName: $typeName, assetImg: $assetImg, py: $py, nickname: $nickname, headPortrait: $headPortrait, headPortraitStoreType: $headPortraitStoreType, showBorder: $showBorder}';
  }
}

class MobileCreateChatGroupPageChangeNotifier extends ChangeNotifier {
  final Logger logger = Logger();

  List<GetContactsListItem> contactsList = [];

  List<ContactsView> contactsViewList = [];

  List<String> pyList = [];

  Set<int> friendUserIdSet = {};

  Future<void> reload() async {
    var result = await HttpUtils.getContactsList();
    contactsList.clear();
    if (ListUtils.isNotEmpty(result.data)) {
      contactsList.addAll(result.data!);
    }
    convertGetContactsListItem2ContactsView();
    notifyListeners();
  }

  void removeFriendUserId(int userId) {
    friendUserIdSet.remove(userId);
    notifyListeners();
  }

  void addFriendUserId(int userId) {
    friendUserIdSet.add(userId);
    notifyListeners();
  }

  void convertGetContactsListItem2ContactsView() {
    Set<String> pySet = {};
    for (var value in contactsList) {
      if (value.nicknamePyPrefixLetter == null) {
        continue;
      }
      pySet.add(value.nicknamePyPrefixLetter!);
    }

    List<String> sortedPyList = pySet.toList();
    sortedPyList.sort((a, b) => a.compareTo(b));
    pyList.clear();
    pyList.addAll(sortedPyList);

    Map<String, List<GetContactsListItem>> groupedGetContactListItemMap = {};
    for (var value in contactsList) {
      var py = value.nicknamePyPrefixLetter;
      var getContactListItemList = groupedGetContactListItemMap[py];
      if (getContactListItemList == null) {
        groupedGetContactListItemMap[py!] = [];
      }
      getContactListItemList = groupedGetContactListItemMap[py];
      getContactListItemList!.add(value);
    }

    contactsViewList.clear();

    for (var py in sortedPyList) {
      var pyData = ContactsView();
      pyData.type = 0;
      pyData.py = py;
      contactsViewList.add(pyData);
      var getContactListItemList = groupedGetContactListItemMap[py];
      if (getContactListItemList != null) {
        for (int i = 0; i < getContactListItemList.length; i++) {
          var value = getContactListItemList[i];
          var contactsView = ContactsView();
          contactsView.type = 1;
          contactsView.contactId = value.id;
          contactsView.contactCode = value.code;
          contactsView.nickname = value.nickname;
          contactsView.headPortrait = value.headPortrait;
          contactsView.headPortraitStoreType = value.headPortraitStoreType;
          // logger.i("i: $i, length: ${getContactListItemList.length}");
          if (i + 1 == getContactListItemList.length) {
            contactsView.showBorder = false;
          }
          contactsViewList.add(contactsView);
        }
      }
    }
  }
}

class MobileCreateChatGroupPage extends StatelessWidget {
  MobileCreateChatGroupPage({super.key});

  final Logger logger = Logger();

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
        providers: [
          ChangeNotifierProvider(create: (context) {
            var result = MobileCreateChatGroupPageChangeNotifier();
            result.reload();
            return result;
          })
        ],
        builder: (context, child) {
          MobileCreateChatGroupPageChangeNotifier
              createChatGroupPageChangeNotifier =
              context.watch<MobileCreateChatGroupPageChangeNotifier>();
          var appUserDetailChangeNotifier =
              context.watch<AppUserDetailChangeNotifier>();
          Color completeBtnBackgroundColor =
              const Color.fromRGBO(8, 193, 94, 1);
          Color completeBtnTextColor = Colors.white;
          if (createChatGroupPageChangeNotifier.friendUserIdSet.isEmpty) {
            completeBtnBackgroundColor = const Color.fromRGBO(234, 234, 234, 1);
            completeBtnTextColor = const Color.fromRGBO(183, 183, 183, 1);
          }
          var contactsViewList =
              createChatGroupPageChangeNotifier.contactsViewList;
          return Scaffold(
              appBar: AppBar(
                title: const Text("发起群聊"),
                centerTitle: true,
                surfaceTintColor:
                    MobileAppGlobalConstants.appBarSurfaceTintColor,
                backgroundColor: MobileAppGlobalConstants.appBarBackgroundColor,
                actions: [
                  GestureDetector(
                    onTap: () {
                      var friendUserIdSet =
                          createChatGroupPageChangeNotifier.friendUserIdSet;
                      if (friendUserIdSet.isEmpty) {
                        return;
                      } else {
                        HttpUtils.createChatGroup(friendUserIdSet)
                            .then((result) async {
                          Conversation conversation = result.data!;
                          AppUserDetail appUserDetail =
                              appUserDetailChangeNotifier.getAppUserDetail();
                          LocalConversation localConversation =
                              LocalConversation.create(
                                  id: conversation.id,
                                  uid1: appUserDetail.id,
                                  chatGroupId: conversation.chatGroupId,
                                  type: conversation.type,
                                  updateTime:
                                      DateTime.now().millisecondsSinceEpoch,
                                  unreadMsgCount: 0);
                          await LocalConversationService.addLocalConversation(
                              localConversation);
                          RouteUtils.pop();
                        });
                      }
                    },
                    child: Container(
                      alignment: Alignment.center,
                      height: 30,
                      margin: const EdgeInsets.only(right: 10),
                      padding: const EdgeInsets.only(left: 10, right: 10),
                      decoration: BoxDecoration(
                          color: completeBtnBackgroundColor,
                          borderRadius: BorderRadius.circular(4)),
                      child: Text(
                        "完成",
                        style: TextStyle(
                            color: completeBtnTextColor, fontSize: 14),
                      ),
                    ),
                  )
                ],
              ),
              body: ListView.builder(
                  itemBuilder: (context, index) {
                    ContactsView contactsView = contactsViewList[index];
                    if (contactsView.type == 0) {
                      return contentViewType0(contactsView);
                    }
                    if (contactsView.type == 1) {
                      return contentViewType1(
                          contactsView, createChatGroupPageChangeNotifier);
                    }
                    return Container();
                  },
                  itemCount: contactsViewList.length));
        });
  }

  /// 拼音展示组件
  Widget contentViewType0(ContactsView contactsView) {
    return Container(
      padding: const EdgeInsets.only(left: 25, right: 25),
      color: const Color.fromRGBO(237, 237, 237, 1),
      alignment: Alignment.centerLeft,
      height: 30,
      child: Text(
        StringUtils.defaultIfEmpty(contactsView.py, "").toUpperCase(),
        style: const TextStyle(
            fontSize: 10, color: Color.fromRGBO(108, 108, 108, 1)),
      ),
    );
  }

  /// 通讯人展示
  Widget contentViewType1(
      ContactsView contactsView,
      MobileCreateChatGroupPageChangeNotifier
          createGroupChatPageChangeNotifier) {
    bool initValue = createGroupChatPageChangeNotifier.friendUserIdSet
        .contains(contactsView.contactId!);
    return Container(
      padding: const EdgeInsets.only(left: 25),
      height: 50,
      child: Row(
        children: [
          Container(
            padding: const EdgeInsets.only(right: 15),
            alignment: Alignment.center,
            child: Checkbox(
                value: initValue,
                onChanged: (value) {
                  if (value == true) {
                    createGroupChatPageChangeNotifier
                        .addFriendUserId(contactsView.contactId!);
                  } else {
                    createGroupChatPageChangeNotifier
                        .removeFriendUserId(contactsView.contactId!);
                  }
                }),
          ),
          Container(
            padding: const EdgeInsets.only(right: 15),
            alignment: Alignment.center,
            child: UserHeadPortrait.network(
                size: 35,
                userCode: contactsView.contactCode!,
                userHeadPortrait: contactsView.headPortrait!,
                userHeadPortraitStoreType: contactsView.headPortraitStoreType!),
          ),
          Expanded(
              child: Container(
            decoration: contactsView.showBorder
                ? const BoxDecoration(
                    border: Border(bottom: BorderSide(color: Colors.black12)))
                : null,
            alignment: Alignment.centerLeft,
            child: Text(
              StringUtils.defaultIfEmpty(contactsView.nickname, ""),
              style: const TextStyle(fontSize: 16),
            ),
          ))
        ],
      ),
    );
  }
}
